package com.drojian.demo2.broadcast.test1;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.drojian.demo.R;

public class BroadcastTest1 extends AppCompatActivity {
    private TextView textView;
    private broadcastReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.part2_activity_broadcast_test1);
        initView();
        initBroadcast();
    }

    private void initView() {
        textView = findViewById(R.id.broadcast_textview);

    }

    private void initBroadcast() {
        IntentFilter filter = new IntentFilter();
        //检测电池电量变化
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        receiver = new broadcastReceiver();
        this.registerReceiver(receiver,filter);
    }


    private class broadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(textView != null){
                textView.setText("当前电量为:" + intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0));
            }

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(receiver != null){
            this.unregisterReceiver(receiver);
        }
    }
}